package model.dao;

import java.io.FileOutputStream;
import java.io.IOException;

import model.dao.hibernate.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.HSQLDialect;

public class GenerateCreateDatabaseTool {

	private final static String OUTPATH = "CreateTables.sql";
	
	public static void main(String[] args) {
		generateAndExecute(new HSQLDialect());
	}

	public static void generateAndExecute(Dialect dialect) {		
		/*String[] scriptDrop = HibernateUtil.getConfig()
				.generateDropSchemaScript(dialect);*/
		String[] scriptCreation = HibernateUtil.getConfig()
				.generateSchemaCreationScript(dialect);
		try {
			FileOutputStream out = new FileOutputStream(OUTPATH);

			//printToOutput(scriptDrop, out);

			printToOutput(scriptCreation, out);

			out.close();

			Session session = HibernateUtil.getSession();
			Transaction transation = session.beginTransaction();
			//runCommandSet(scriptDrop, session);
			runCommandSet(scriptCreation, session);
			transation.commit();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void runCommandSet(String[] scriptDrop, Session session) {
		for (String string : scriptDrop) {
			session.createSQLQuery(string).executeUpdate();
		}
	}

	private static void printToOutput(String[] scriptDrop, FileOutputStream out)
			throws IOException {
		for (String string : scriptDrop) {
			out.write((string + ";\n").getBytes());
		}
	}

}
